#encoding:utf8
#
#个人的常用功能函数或类
#
#
#------------------------------函数：不连续子串判断-------------------
def isSubStrNotSeried(subStr,rareStr):
    '''
    判断类似'ertsat'是否为'1er334t43sat2'的不连续子串，假定子串长度不大于长串
    subStr:子串
    rareStr:长串
    '''
    if len(subStr)==0:
        return True
    if len(subStr)>len(rareStr):
        return False
    subStart =0
    subIndex=1
    subEnd =len(subStr)
    rareStart =0
    rareIndex=1
    rareEnd=len(rareStr)
    while True:
        while subStr[subStart] != rareStr[rareStart]:
            rareStart +=1
            rareIndex=rareStart+1
            if rareStart==rareEnd:#长字符结束
                return False

        while subStr[subStart:subIndex] in rareStr[rareStart:rareIndex]:
            if subIndex==subEnd:#短字符结束
                return True
            if rareIndex==rareEnd:
                return False
            subIndex +=1
            rareIndex +=1
        subStart=subIndex-1
        rareStart=rareIndex-1
#-------------------------------函数：去除txt的BOM头-----------------------------
import codecs
def cutBom(txtName,writeback=False):
    with open(txtName,'r') as rfile:
        data=rfile.read()
        if data[:3]==codecs.BOM_UTF8:
            data=data[3:]
            if writeback==True:
                with open('%s-%s'%('',txtName),'w') as wfile:
                    wfile.write(data)
        return data
#-------------------------------类：守护线程-----------------------------
import threading
class BeDaemoning(threading.Thread):
    '''
    线程的守护线程，侦测线程是否存活，如果崩溃则从重启
    用法：
        初始化守护线程
            daem=BeDaemoning()
            daem.start()
        添加被守护的线程
            daem.addThread(threadName,thread,threadAction,actionArgs)
        移除被守护的线程
            daem.removeThread(threadName)
    '''
    def __init__(self):
        super(BeDaemoning,self).__init__()
        self.threadList={}
        self.flag=True

    def run(self):
        import time
        while self.flag==True:
            for name in self.threadList.keys():
                threadItem =self.threadList[name]
                if threadItem[0].is_alive()==False:
                    print 'rebulid thread'
                    thread=threading.Thread(target=threadItem[1],args=threadItem[2])
                    self.threadList[name]=(thread,threadItem[1],threadItem[2])
                    thread.setDaemon(True)
                    thread.start()
            time.sleep(5)

    def setFlag(self,flag):
        self.flag=flag

    def addThread(self,threadName,tgThread,action,actionArgs):
        self.threadList[threadName]=(tgThread,action,actionArgs)

    def removeThread(self,threadName):
        del self.threadList[threadName]

    def clearList(self):
        self.threadList.clear()

#--------------------------------函数：编码识别--------------------------------
def detect(st):
    '''
    利用chardet模块，识别字符串编码
    比如：detect('中文')，结果{'confidence': 0.7525, 'encoding': 'utf-8'}
    '''
    if isinstance(st,unicode):
        return {'confidence':1,'encoding':'unicode'}
    import chardet
    return chardet.detect(st)
#-------------------------------函数：json格式配置文件-------------------------
def loadArchive(uri,errorMeg='指定的文件不存在'):
    '''
    从指定路径加载配置信息，返回字典
    '''
    import json
    try:
        with open(uri,'r') as archive:
            dic =json.loads(archive.read())
            return dic
    except IOError,e:
        print errorMeg
        raise IOError,errorMeg
def saveArchive(uri,dic):
    '''
    保存配置信息到指定路径
    '''
    import json
    with open(uri,'w') as archive:
        archive.write(json.dumps(dic))
#-------------------------------函数：自动另存为的日志-----------------------------
def getLogger(uri,maxSize=1000000):
    import logging
    from logging.handlers import RotatingFileHandler
    logger=logging.getLogger('A')
    logger.setLevel(logging.DEBUG)
    logfile=RotatingFileHandler(uri,maxBytes=maxSize,backupCount=1000)
    logger.addHandler(logfile)
    return logger
#------------------------------函数：html实体转换-------------------------------
def escapeHtml(html):
    import cgi
    return cgi.escape(html)
def unescapeHtml(html):
    import HTMLParser
    return HTMLParser.HTMLParser().unescape(html)
#------------------------------函数：发送邮件--------------------------------
def send_mail(mail_user,mail_pass,mail_host,mailto_list, sub, content):
    from email.mime.text import MIMEText
    import smtplib

    me = "LogServer"+"<"+mail_user+">"
    msg = MIMEText(content, _subtype='plain', _charset='utf-8')
    msg['Subject'] = sub    
    msg['From'] = me
    msg['To'] = ";".join(mailto_list)
    try:
        server = smtplib.SMTP()
        server.connect(mail_host)
        server.login(mail_user, mail_pass)
        server.sendmail(me, mailto_list, msg.as_string())
        server.close()
        return True
    except Exception, e:
        print str(e)
        return False
#-----------------------函数：抓取网页----------------------------
def openUrl(url, data=None,header={}):
    resp =None
    request =urllib2.Request(url, data, header)
    response =urllib2.urlopen(request,timeout=3)
    resp = response.read()

def openUrl(url,data=None,header={},proxyList=None):
    import urllib2,urllib
    request=urllib2.Request(url,data,headers)

    if proxyList!=None:
        proxy_handler=urllib2.ProxyHandler(proxyList)
    else:
        proxy_handler=urllib2.ProxyHandler({})
    opener=urllib2.build_opener(proxy_handler)
    urllib2.install_opener(opener)
    response =urllib2.urlopen(request,timeout=6)
    return response.read().decode('utf8')
#---------------------------类：Adsl连接------------------------------
#encoding:utf8
import os
import time
class Adsl(object):
    #==============================================================================
    # __init__ : name: adsl名称
    #==============================================================================
    def __init__(self,adslname,  username, password):
        self.name = adslname
        self.username = username
        self.password = password
    #==============================================================================
    # set_adsl : 修改adsl设置
    #==============================================================================
    def set_adsl(self,adslname, username, password):
        self.name = adslname
        self.username = username
        self.password = password
    #==============================================================================
    # connect : 宽带拨号
    #==============================================================================
    def connect(self):
        cmd_str = "rasdial %s %s %s" % (self.name, self.username, self.password)
        res =os.system(cmd_str)
        time.sleep(5)
        return res
    #==============================================================================
    # disconnect : 断开宽带连接
    #==============================================================================
    def disconnect(self):
        cmd_str = "rasdial %s /disconnect" % self.name
        res =os.system(cmd_str)
        time.sleep(5)
        return res
    #==============================================================================
    # reconnect : 重新进行拨号
    #==============================================================================
    def reconnect(self):
        a =self.disconnect()
        b =self.connect()
        return (a, b)
#------------------------------方法：字符串时间和时间戳转换------------------------
#将字符串时间转化为时间戳
def str2Unixtime(strTime):
    import time
    return time.mktime(time.strptime(strTime,'%Y-%m-%d %H:%M:%S'))
#将时间戳转化为字符串时间
def unixtime2Str(unixtime):
    import time
    return time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(unixtime))

if __name__=='__main__':
    url='C:\Documents and Settings\Administrator\code.json'
    loadArchive(url)
